package com.waterms.service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import com.waterms.dao.UserDao;
import com.waterms.model.User;

public class UserServiceImpl implements UserService {
	private UserDao userDao;

	public void addUser(User user) {
		user.setPassword(encodeMD5(user.getUsername()));
		userDao.addUser(user);
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	public  String encodeMD5(String str) {
		if (str == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder();
		try {
			MessageDigest code = MessageDigest.getInstance("MD5");
			code.update(str.getBytes());
			byte[] bs = code.digest();
			for (int i = 0; i < bs.length; i++) {
				int v = bs[i] & 0xFF;
				if (v < 16) {
					sb.append(0);
				}
				sb.append(Integer.toHexString(v));
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return sb.toString().toUpperCase();
	}
	
	public boolean checkUsername(String username){
		List users = userDao.checkUsername(username);
		if (users == null ||  users.size() == 0)
		{
			return false;
		}else{
		    return true;
		}
	}
	
	public boolean checkUser(User user){
		if (checkUsername(user.getUsername())){
			List us = userDao.checkUsername(user.getUsername());
			int count = us.size();
			int i;
			for( i = 0;i<count;i++){
				User u = (User)us.get(i);
				if (u.getPassword().equals(encodeMD5(user.getPassword()))){
					break;
				}
			}
			System.out.println(i);
			System.out.println(count);
				return true;
				
		}else{
			return false;
		}
		
	}
	
	

}
